package net.homeip.dometec.autodownloadrcsqt;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;

import net.homeip.dometec.autodownloadrcsqt.utils.CLabel;
import net.homeip.dometec.autodownloadrcsqt.utils.OSValidator;
import net.homeip.dometec.autodownloadrcsqt.utils.OperUrl;

public class MainWindow extends JFrame {

	private static final long serialVersionUID = 1L;

	public static final NumberFormat nf = new DecimalFormat("00");
	public static final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
	public static final SimpleDateFormat fds = new SimpleDateFormat("yyyyMMdd");

	public static final String CONFIG_FILE = System.getProperty("user.home") + File.separatorChar + ".rcsqt/" + File.separatorChar
			+ "config.properties";

	private static File conf = new File(CONFIG_FILE);
	private JLabel label;
	private CLabel clabel;
	private JProgressBar progressBar;

	public static void main(String[] args) {

		nf.setMinimumIntegerDigits(2);

		if (!conf.isFile()) {
			conf.getParentFile().mkdirs();
			new ConfigWindow(conf, true);
		} else {
			new MainWindow();
		}

	}

	public MainWindow() {

		final File conf = new File(CONFIG_FILE);

		setTitle("Download Automatico Quotidiani RCS");
		setSize(500, 180);

		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});

		SpringUtilities.centerWindow(this);

		setLayout(new GridBagLayout());

		label = new JLabel("Autenticazione...");
		GridBagConstraints c = new GridBagConstraints();
		c.insets = new Insets(10, 10, 10, 10);
		c.gridwidth = 2;
		c.gridx = 0;
		c.gridy = 1;
		add(label, c);

		progressBar = new JProgressBar(0, 100);
		progressBar.setValue(0);
		progressBar.setStringPainted(true);
		c = new GridBagConstraints();
		c.insets = new Insets(10, 10, 10, 10);
		c.gridx = 0;
		c.gridy = 2;
		add(progressBar, c);

		ImageIcon icon = new ImageIcon(getClass().getClassLoader().getResource("config.png"), "Opzioni...");
		JButton optBtn = new JButton("Opzioni...", icon);
		optBtn.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				new ConfigWindow(conf);
			}
		});
		c = new GridBagConstraints();
		c.insets = new Insets(10, 10, 10, 10);
		c.gridx = 1;
		c.gridy = 2;
		add(optBtn, c);

		clabel = new CLabel("termini e condizioni");
		clabel.setClickable(true, new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				OperUrl.showInBrowser("http://code.google.com/p/autodownload-rcsqt/wiki/TerminiECondizioni", null);
			}
		}, null);
		c = new GridBagConstraints();
		c.insets = new Insets(0, 0, 0, 0);
		c.gridwidth = 2;
		c.gridx = 0;
		c.gridy = 3;
		add(clabel, c);

		pack();
		setVisible(true);

		showPDF(conf, "CORSE", "CORRIEREFC", ".corriere.it");
		showPDF(conf, "GAZZA", "GAZZETTAFC", ".gazzetta.it");

	}

	private void showPDF(final File conf, String cli, String group, String hostTestata) {

		try {

			Properties prop = new Properties();
			prop.load(new FileInputStream(conf));
			String user = prop.getProperty("user");
			String pass = prop.getProperty("pass");
			String outdir = prop.getProperty("outdir");
			Boolean closeonend = new Boolean(prop.getProperty("closeonend"));

			HttpAccess httpAccess = new HttpAccess(cli, group, hostTestata);

			label.setText("Autenticatione...");
			this.repaint();
			boolean autenticated = httpAccess.autentica(user, pass);

			if (!autenticated) {

				label.setText("Non autenticato");
				this.repaint();

			} else {

				label.setText("Apertura sessione...");
				this.repaint();
				boolean openSession = httpAccess.openSession();

				if (!openSession) {

					label.setText("Sessione non aperta");
					this.repaint();

				} else {

					label.setText("Recupero indice giornali...");
					this.repaint();

					List<Map<String, String>> edizioni = httpAccess.getPubblicazioniEdizioni();

					// Se l'edizione non è scaricata, la scarico e la apro
					for (Map<String, String> map : edizioni) {
						File file = new File(outdir + File.separator + map.get("CommonFileName") + ".pdf");
						if (!file.exists()) {

							label.setText("Recupero pdf " + map.get("TESTATA_ESTESA") + "/" + map.get("EDIZIONE_INTERNA") + "...");
							this.repaint();

							boolean b = false;

							for (int i = 0; i < 3; i++) {
								b = httpAccess.getPdf(file, map.get("Cod_Testata"), map.get("Cod_Edizione"), map.get("MaxData"), this,
										progressBar);
								if (b && file.length() > 0)
									break;
							}

							if (!b || file.length() == 0) {
								System.out.println("Problema nel recupero di " + map.toString());
							} else {
								openPDF(file.getAbsolutePath());
							}

						}
					}

					label.setText("Finito.");
					progressBar.setValue(progressBar.getMaximum());
					this.repaint();

				}
			}

			if (closeonend)
				System.exit(0);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void openPDF(String filename) throws IOException {
		if (filename.endsWith(".pdf")) {
			if (OSValidator.isWindows())
				Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + filename);
			else if (OSValidator.isMac())
				Runtime.getRuntime().exec("open " + filename);
			else if (OSValidator.isUnix())
				Runtime.getRuntime().exec(new String[] { "okular", filename });
		}
	}

}
